# coding:utf-8
"""
description:登录邮件并获取最新邮件解析内容
"""
import configparser
import email
import imaplib
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import re

import poplib
from config.GlobalParameter import CONFIG_DIR
from common.Log import LOG


def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset


def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value


def print_info(msg, indent=0):
    if indent == 0:
        for header in ['From', 'To', 'Subject']:
            value = msg.get(header, '')
            if value:
                if header == 'Subject':
                    value = decode_str(value)
                else:
                    hdr, addr = parseaddr(value)
                    name = decode_str(hdr)
                    value = u'%s <%s>' % (name, addr)
            # print('%s%s===: %s' % ('  ' * indent, header, value))

    if (msg.is_multipart()):
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            # print('%spart %s' % ('  ' * indent, n))
            # print('%s--------------------' % ('  ' * indent))
            print_info(part, indent + 1)
    else:
        content_type = msg.get_content_type()
        if content_type == 'text/plain' or content_type == 'text/html':
            content = msg.get_payload(decode=True)
            charset = guess_charset(msg)
            if charset:
                content = content.decode(charset)
                LOG.info('%sText: %s' % ('  ' * indent, content))
                return re.findall('\d+', str(content))[0]  # 根据正则表达式\d+获取四位邮件验证码数字
        # else:
        #     print('%sAttachment: %s' % ('  ' * indent, content_type))


def get_emailcontent():
    """读取config下的ini文件"""
    conData = configparser.ConfigParser()
    conData.read(CONFIG_DIR, encoding='utf-8')
    FromName = conData.get("EmailUser", "email_name")
    Serv = conData.get("EmailUser", "smtp_sever")
    Pwd = conData.get("EmailUser", "email_password")

    try:
        # 连接到POP3服务器:
        server = poplib.POP3_SSL(Serv, 995)
        # 可以打开或关闭调试信息:
        server.set_debuglevel(1)
        server.user(FromName)
        server.pass_(Pwd)
        resp, mails, octets = server.list()  # list()返回所有邮件的编号
        index = len(mails)  # 获取最新一封邮件, 注意索引号从1开始
        resp, lines, octets = server.retr(index)
        msg_content = b'\r\n'.join(lines).decode('utf-8')  # lines存储了邮件的原始文本的每一行,获得整个邮件的原始文本
        msg = Parser().parsestr(msg_content)  # 解析出邮件
        # server.dele(index)    # 可以根据邮件索引号直接从服务器删除邮件
        server.quit()  # 关闭连接
        return print_info(msg)
    except:
        # 连接到imap服务器:
        server = imaplib.IMAP4_SSL(Serv)
        server.login(FromName, Pwd)
        # 邮箱中的文件夹，默认为'INBOX'
        inbox = server.select("INBOX")
        # 搜索匹配的邮件，第一个参数是字符集，None默认就是ASCII编码，第二个参数是查询条件，这里的ALL就是查找全部
        type, data = server.search(None, "ALL")
        # 邮件列表,使用空格分割得到邮件索引
        msgList = data[0].split()
        # 最新邮件，第0封邮件为最早的一封邮件
        latest = msgList[len(msgList) - 1]
        type, datas = server.fetch(latest, '(RFC822)')
        # 使用utf-8解码
        text = datas[0][1].decode('utf8')
        # 转化为email.message对象
        message = email.message_from_string(text)
        return print_info(message)
